import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';

import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();
    const exceptionResponse = exception.getResponse();
    
    let message: string;
    if (typeof exceptionResponse === 'string') {
      message = exceptionResponse;
    } else if (typeof exceptionResponse === 'object' && 'message' in exceptionResponse) {
      message = (exceptionResponse as { message: string | string[] }).message as string;
      if (Array.isArray(message)) {
        message = message.join(', ');
      }
    } else {
      message = 'An error occurred';
    }

    const responseBody = {
      code: status,
      message: message,
      data: null,
    };

    // 注意：这里我们保持 HTTP 为200 ，更具返回的数据code进行判断
    response.status(HttpStatus.OK).json(responseBody);
  }
}
